package app.modules.cloudpivot.sso;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.web.sso.exception.UserException;
import com.authine.cloudpivot.web.sso.security.BaseAuthenticationToken;
import com.authine.cloudpivot.web.sso.template.BaseSimpleTemplate;
import com.authine.cloudpivot.web.sso.template.ResponseTypeEnum;
import com.authine.cloudpivot.web.sso.template.SimpleTemplateConfig;
import com.authine.cloudpivot.web.sso.view.ThreadLocalValue;

import app.modules.cloudpivot.utils.RSAUtil;

/**
 * 免登接口<br>
 * code
 *
 * @author LiuGangQiang Create in 2024/12/09
 */
@Component
public class ThirdpartyAuth extends BaseSimpleTemplate {
    private final static Logger LOG = LoggerFactory.getLogger(ThirdpartyAuth.class);

    @Value("${expand.sso.thirdparty.rsa.privatekey}")
    private String privateKey;

    @Value("${expand.sso.thirdparty.rsa.difference:5}")
    private Integer difference;

    protected ThirdpartyAuth() {
        super(SimpleTemplateConfig.builder()
                .requestMatcher(new AntPathRequestMatcher("/login/thirdparty", HttpMethod.GET.name()))
                .responseType(ResponseTypeEnum.JSON)
                .redirectClientID("api")
                .redisTokenKey("thirdparty_access_token")
                .redisTicketKey("thirdparty_ticker")
                .build());
    }

    @Override
    public String getSourceId(BaseAuthenticationToken token) throws Exception {
        /* 获取密文 */
        String cipher = token.getCode();
        /* 解密获取原文 */
        String original = RSAUtil.getInstance().RSADecode(privateKey, cipher);
        /* 校验是否是一个JSON字符串 */
        if (JSONValidator.from(original).validate()) {
            /* 转换成JSON对象 */
            JSONObject originalObject = JSONObject.parseObject(original);
            /* 获取时间戳 */
            Long targetTime = originalObject.getLongValue("timestamp");
            /* 获取当前时间 */
            Long currentTime = System.currentTimeMillis();
            /* 计算偏差范围 */
            Long range = difference * 60 * 1000L;
            /* 判断时间是否在范围内 */
            if (targetTime <= currentTime && targetTime >= (currentTime - range)) {
                String userId = originalObject.getString("uid");
                LOG.info("===>>第三方平台免登调用 UID:{} CropId:{}", userId, ThreadLocalValue.localCorpId.get());
                return userId;
            } else {
                throw new UserException("原文时间戳不对");
            }
        } else {
            throw new UserException("原文格式不对请检查");
        }
    }

    @Override
    public UserModel getUser(Object sourceId) {
        return engineService.getOrganizationFacade().getUserByUserIdAndCorpId(sourceId.toString(), ThreadLocalValue.localCorpId.get());
    }
}
